import { VNode } from "vue";
import { Popup } from "../popup";
import DrawerVue from "./drawer.vue";
import { DrawerOptions } from "./type";
import { BasicFormBox } from "../../basic-form-box";
import { ButtonGroup } from "../../button-group";
import { BasicFormOptions } from "../../basic-form-box/type";
import { FORM_BOX_METHOD, repaintProxy } from "@pkg";

interface DrawerFormOptions {
	/** 是否打开弹出层进行表单重置，默认重置 */
	isReset?: boolean;
	type?: BasicFormOptions<any>["type"];
	labelWidth?: BasicFormOptions<any>["labelWidth"];
}
export class Drawer extends Popup<DrawerOptions> {
	private formInstance!: BasicFormBox;
	private buttonGroup!: ButtonGroup;
	constructor() {
		super(DrawerVue);
	}
	/**
	 * 初始化表单
	 * @param callback 表单初始化的回调
	 * @param isReset 是否唤起表单时进行表单重置，默认重置
	 * @returns
	 */
	initForm<Form = Record<string, any>>(
		callback: (form: BasicFormBox<Form>, others?: { btn: ButtonGroup }) => void,
		config?: DrawerFormOptions
	): Drawer {
		this.formInstance = new BasicFormBox({
			...{
				type: "edit",
				layout: "vertical",
				options: [],
			},
			...config,
		});
		this.buttonGroup = new ButtonGroup();
		if (config?.isReset) {
			this.formInstance.reset();
		}
		callback &&
			callback(this.formInstance as BasicFormBox<Form>, {
				btn: this.buttonGroup,
			});
		return this;
	}
	initButton<Form = Record<string, any>>(
		callback: (btn: ButtonGroup, others?: { form: BasicFormBox<Form> }) => void
	) {
		callback &&
			callback(this.buttonGroup, {
				form: this.formInstance as BasicFormBox<Form>,
			});
		return this;
	}
	open(opts: DrawerOptions) {
		const res = this.showPopup(opts, false);
		this.formInstance = repaintProxy(
			this.formInstance,
			key => {
				return FORM_BOX_METHOD.includes(key);
			},
			() => {
				res.repaint();
			}
		);
		return {
			getFormInstance: () => {
				return this.formInstance;
			},
			shutDown: res.shutDown,
		};
	}
	getContentVNode(): VNode {
		return this.formInstance.getVNode();
	}
	getBottomVNode(): VNode {
		return this.buttonGroup.getVNode();
	}
}

const drawer = new Drawer();
export { drawer };
